package org.example.cloudapply.interceptors;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.cloudapply.utils.JwtUtil;
import org.example.cloudapply.utils.ThreadLocalUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


import java.util.Map;

//登录验证jwt，然后传输请求头。
//拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate stringRedisTemplate;

    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        try {
            //从redis中拿到相同的token
            ValueOperations<String,String> ops=stringRedisTemplate.opsForValue();
            String jwtToken = ops.get(token);
            if(jwtToken==null){
                throw new RuntimeException();
            }
            Map<String,Object> claims= JwtUtil.parseToken(token);
            //将解析出来的对象放进线程池，隔离线程
            ThreadLocalUtil.set(claims);
            return true;
        }
        catch (Exception e){}
        response.setStatus(401);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空线程池，防止内存泄露
        ThreadLocalUtil.remove();
    }
}
